using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace BSDS.Core.Data.Remote.Account
{
    public class AccountRequestSerializer
    {
        public IEnumerable<DataSourceInfo> ParseDataSourcesXml(string xmlText)
        {
            const string appns = "http://www.w3.org/2007/app";
            const string atomns = "http://www.w3.org/2005/Atom";
            const string bsins = "http://schemas.microsoft.com/bing/spatial/2010/11/odata";

            var xmlDocument = XDocument.Parse(xmlText);

            var dataSources = xmlDocument.Descendants(XName.Get("workspace", appns))
                .Select(xe => new DataSourceInfo
                        (
                        xe.Descendants(XName.Get("title", atomns)).First().Value,
                        xe.Descendants(XName.Get("title", atomns)).Skip(1).First().Value,
                        xe.Descendants(XName.Get("collection", appns)).Attributes(XName.Get("href", appns)).First().Value,
                        xe.Attributes(XName.Get("updated", bsins)).First().Value
                        ));

            // Correct and localize the last publish time
            var ds = dataSources.ToList();
            foreach (var d in ds)
            {
                var dt = DateTime.Parse(d.LastUpdate); // This will convert the time to local time since it is in standard UTC format
                
                // BUG FIX: Add 2 hours to compensate for a bug in BSDS which reports time as UTC-1
                dt = dt.Add(new TimeSpan(1, 0, 0)); 

                d.LastUpdate = dt.ToString();
            }

            return ds;
        }
    }
}